<template>
  <el-dialog
    :visible.sync="isShow"
    :title="mode === 'add' ? '新增部门' : '编辑部门'"
    width="500"
  >
    <el-form
      v-if="bol"
      ref="form"
      label-width="100px"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          @focus="focusEvent"
        ><el-option
          v-for="i in userList"
          :key="i.id"
          :label="i.username"
          :value="i.username"
        /></el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysUserSimple, addDepartment, editDepartment } from '@/api/department'
export default {
  name: 'DialogItem',
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add',
      bol: true,
      isShow: false,
      userList: [],
      form: {
        name: '', //	string	非必须		部门名称
        code: '', //	string	非必须		部门编码，同级部门不可重复
        manager: '', //	string	非必须		负责人名称
        introduce: '', //	string	非必须		介绍
        pid: '' //	string	非必须		父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let tempName = ''
              if (this.mode === 'add') {
                tempName = this.initList.filter((item) => {
                  return item.pid === this.item.id
                })
              } else {
                tempName = this.initList.filter((item) => {
                  return item.pid === this.item.pid && item.id !== this.item.id // 排除自己
                })
              }
              const result = tempName.some((item) => {
                return item.name === value.trim()
              })
              result
                ? callback(new Error('不能输入同名字段：' + value))
                : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                result = this.initList.some((item) => {
                  return item.code === value
                })
              } else {
                result = this.initList.some((item) => {
                  return item.code === value && item.id !== this.item.id
                })
              }
              result
                ? callback(new Error('不能输入同名字段：' + value))
                : callback()
            },
            trigger: 'change'
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      },
      item: ''
    }
  },
  watch: {
    isShow: {
      handler(newVal) {
        // immediate:true,
        // deep:true,  // 默认只监听栈的变化 ，deep:true,监听堆与栈的变化
        if (!newVal) {
          // 还原表单数据
          this.form = {
            name: '', //	string	非必须		部门名称
            code: '', //	string	非必须		部门编码，同级部门不可重复
            manager: '', //	string	非必须		负责人名称
            introduce: '', //	string	非必须		介绍
            pid: '' //	string	非必须		父级部门ID
          }
          // 关闭表单，还原初始值，关闭验证
          this.$refs.form.resetFields()
        }
      }
    }
  },
  mounted() {
    this.$bus.$on('changeShow', (bol, item, mode = 'add') => {
      this.isShow = bol
      this.item = item // 接受bus传值
      this.mode = mode
      if (mode === 'edit') {
        // console.log(item)
        // console.log(JSON.parse(JSON.stringify(item)))
        this.form = JSON.parse(JSON.stringify(item))
        // console.log(this.form)
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('changeShow')
  },
  methods: {
    async focusEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
      }
    },
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await addDepartment(this.form)
          } else {
            console.log(this.form)
            await editDepartment(this.form)
          }
          this.$message.success(this.mode === 'add' ? '新增成功' : '修改成功')
          this.isShow = false
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
